/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》  http://lblbc.cn/blog
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 */
<template>
  <div>
    <s-header :name="'收货地址'" :back="from == 'create-order' ? '' : '/settings'"></s-header>
    <div>
      <van-address-list
        v-if="from != 'mine'"
        v-model="selectedAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="onSelect"
      />
      <van-address-list
        v-else
        v-model="selectedAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
      />
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted } from 'vue'
import sHeader from '@/components/MyHeader'
import { getAddressList } from '@/service/axios-services'
import { useRoute, useRouter } from 'vue-router'
export default {
  components: {
    sHeader
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      selectedAddressId: '1',
      list: [],
      from: route.query.from
    })

    onMounted(async () => {
      const { data } = await getAddressList()
      if (!data) {
        state.list = []
        return
      }
      state.list = data.map(item => {
        return {
          id: item.id,
          name: item.name,
          tel: item.phone,
          address: item.address,
          isDefault: item.defaultAddress
        }
      })
    })

    const onAdd = () => {
      router.push({ path: '/address', query: { type: 'add', from: state.from }})
    }

    const onEdit = (item) => {
      router.push({ path: 'address', query: { type: 'edit', addressId: item.id, from: state.from }})
    }

    const onSelect = (item) => {
      if( state.from =='create-order' ){
        router.push({ path: 'create-order', query: { addressId: item.id, from: state.from }})
      }
    }

    return {
      ...toRefs(state),
      onAdd,
      onEdit,
      onSelect
    }
  }
}
</script>

<style>
  .van-radio__icon {
    display: none;
  }
  .van-button {
    background: #EF3965;
    border-color: #EF3965;
  }
</style>